// https://www.sporttery.cn/jc/jsq/zqspf/
const axios = require('axios');

// interface OddsItem {
//     a: string;           // 客胜赔率
//     af: string;          // 客胜赔率变化方向 (1: 上升, -1: 下降, 0: 无变化)
//     d: string;           // 平局赔率
//     df: string;          // 平局赔率变化方向
//     goalLine: string;    // 让球线
//     goalLineValue: string; // 让球数值
//     h: string;           // 主胜赔率
//     hf: string;          // 主胜赔率变化方向
//     updateDate: string;  // 更新日期 (YYYY-MM-DD)
//     updateTime: string;  // 更新时间 (HH:mm:ss)
// }

// interface Odds {
//     had: OddsItem;   // 胜平负玩法
//     hhad: OddsItem;  // 让球胜平负玩法
// }

// interface MatchData {
//     odds: Odds;
// }

// 1 获取所有当前可买比赛数据
async function getAllMatches() {
  try {
    // API URL和参数
    const API_URL = 'https://webapi.sporttery.cn/gateway/uniform/football/getMatchCalculatorV1.qry';
    const API_PARAMS = {
      poolCode: 'hhad,had', // 获取胜平负和让球胜平负
      channel: 'c'
    };

    console.log('正在获取全部比赛数据...');
    const response = await axios.get(API_URL, { params: API_PARAMS });

    // 验证请求是否成功
    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    const matchInfoList = response.data.value.matchInfoList || [];
    let totalMatches = 0;

    // 计算总比赛数量
    matchInfoList.forEach(dateInfo => {
      totalMatches += (dateInfo.subMatchList || []).length;
    });

    console.log(`成功获取比赛数据，共 ${matchInfoList.length} 天, ${totalMatches} 场比赛`);

    return response.data;
  } catch (error) {
    console.error('获取全部比赛数据出错:', error.message);
    throw error;
  }
}

// 2 获取当天所有比赛数据
async function getFormattedMatches() {
  try {
    const allData = await getAllMatches();
    const formattedMatches = [];

    // 遍历每一天的比赛
    allData.value.matchInfoList.forEach(dateInfo => {
      const businessDate = dateInfo.businessDate;
      const weekday = dateInfo.weekday;

      // 遍历该天的所有比赛
      (dateInfo.subMatchList || []).forEach(match => {
        formattedMatches.push({
          matchId: match.matchId,
          matchNum: match.matchNumStr,
          matchTime: `${businessDate} ${match.matchTime}`,
          weekday: weekday,
          leagueId: match.leagueId,
          leagueName: match.leagueAbbName,
          homeTeam: {
            id: match.homeTeamId,
            name: match.homeTeamAbbName,
            fullName: match.homeTeamAllName,
            rank: match.homeRank
          },
          awayTeam: {
            id: match.awayTeamId,
            name: match.awayTeamAbbName,
            fullName: match.awayTeamAllName,
            rank: match.awayRank
          },
          odds: {
            had: match.had || {}, // 胜平负赔率
            hhad: match.hhad || {} // 让球胜平负赔率
          }
        });
      });
    });

    return formattedMatches;
  } catch (error) {
    console.error('获取格式化比赛数据出错:', error.message);
    throw error;
  }
}

// 3 获取球队历史比赛数据
async function getTeamHistoryMatches(params) {
  try {
    // 发送API请求
    const url = 'https://webapi.sporttery.cn/gateway/uniform/football/team/getMatchResultV1.qry';
    const response = await axios.get(url, { params });

    // 验证响应数据
    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    return response.data?.value?.matchList || [];
  } catch (error) {
    console.error('获取球队历史比赛数据出错:', error.message);
    throw error;
  }
}

// 4 获取比赛的积分榜数据
async function getMatchTables(gmMatchId) {
  try {
    const url = 'https://webapi.sporttery.cn/gateway/uniform/football/getMatchTablesV2.qry';
    const response = await axios.get(url, {
      params: { gmMatchId }
    });

    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    return response.data.value;
  } catch (error) {
    console.error('获取积分榜数据出错:', error.message);
    throw error;
  }
}
// 格式化积分榜数据，提取关键信息
async function formatTablesData(gmMatchId) {
  const tablesData = await getMatchTables(gmMatchId)
  if (!tablesData) return null;

  const formatTeamData = (teamData) => {
    if (!teamData) return null;

    return {
      总积分榜: {
        球队: teamData.total?.teamShortName || '',
        排名: teamData.total?.ranking || '',
        积分: teamData.total?.points || '',
        场次: teamData.total?.totalLegCnt || 0,
        胜: teamData.total?.winGoalMatchCnt || 0,
        平: teamData.total?.drawMatchCnt || 0,
        负: (teamData.total?.totalLegCnt || 0) - (teamData.total?.winGoalMatchCnt || 0) - (teamData.total?.drawMatchCnt || 0),
        进球: teamData.total?.goalCnt || 0,
        失球: teamData.total?.lossGoalCnt || 0,
        净胜球: teamData.total?.netGoal || 0,
        胜率: teamData.total?.winProbability || '0%'
      },
      主场积分榜: {
        球队: teamData.home?.teamShortName || '',
        排名: teamData.home?.ranking || '',
        积分: teamData.home?.points || '',
        场次: teamData.home?.totalLegCnt || 0,
        胜: teamData.home?.winGoalMatchCnt || 0,
        平: teamData.home?.drawMatchCnt || 0,
        负: (teamData.home?.totalLegCnt || 0) - (teamData.home?.winGoalMatchCnt || 0) - (teamData.home?.drawMatchCnt || 0),
        进球: teamData.home?.goalCnt || 0,
        失球: teamData.home?.lossGoalCnt || 0,
        净胜球: teamData.home?.netGoal || 0,
        胜率: teamData.home?.winProbability || '0%'
      },
      客场积分榜: {
        球队: teamData.away?.teamShortName || '',
        排名: teamData.away?.ranking || '',
        积分: teamData.away?.points || '',
        场次: teamData.away?.totalLegCnt || 0,
        胜: teamData.away?.winGoalMatchCnt || 0,
        平: teamData.away?.drawMatchCnt || 0,
        负: (teamData.away?.totalLegCnt || 0) - (teamData.away?.winGoalMatchCnt || 0) - (teamData.away?.drawMatchCnt || 0),
        进球: teamData.away?.goalCnt || 0,
        失球: teamData.away?.lossGoalCnt || 0,
        净胜球: teamData.away?.netGoal || 0,
        胜率: teamData.away?.winProbability || '0%'
      }
    };
  };

  return {
    联赛信息: {
      联赛: tablesData.leagueShortName || '',
      赛季: tablesData.seasonName || '',
      阶段: tablesData.homeTables?.total?.phaseName || ''
    },
    主队数据: formatTeamData(tablesData.homeTables),
    客队数据: formatTeamData(tablesData.awayTables)
  };
}

// 5 获取比赛赔率变化 https://www.sporttery.cn/jc/zqdz/index.html?showType=3&mid=2033598
/**
 * 下注方式类型定义
 */
const BET_TYPES = {
  HAD: {
    key: 'hadList',
    name: '胜平负固定奖金',
    description: '主队胜(H)、平局(D)、客队胜(A)',
    fields: ['h', 'd', 'a']
  },
  HHAD: {
    key: 'hhadList',
    name: '让球胜平负固定奖金',
    description: '让球胜平负，包含让球数',
    fields: ['h', 'd', 'a', 'goalLine']
  },
  CRS: {
    key: 'crsList',
    name: '比分固定奖金',
    description: '准确比分投注',
    fields: ['s00s00', 's00s01', 's00s02', 's01s00', 's01s01', 's02s00', 's02s01', 's03s00', 's04s00', 's05s00', 's-1sd', 's-1sh', 's-1sa']
  },
  TTG: {
    key: 'ttgList',
    name: '总进球数固定奖金',
    description: '全场总进球数0-7+球',
    fields: ['s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7']
  },
  HAFU: {
    key: 'hafuList',
    name: '半全场胜平负固定奖金',
    description: '半场/全场结果组合',
    fields: ['hh', 'hd', 'ha', 'dh', 'dd', 'da', 'ah', 'ad', 'aa']
  }
};
/**
 * 获取赔率变化情况
 * @param {string} matchId - 比赛ID
 * @returns {Promise<Object>} 返回赔率变化数据
 */
async function getOddsHistory(matchId) {
  try {
    const API_URL = 'https://webapi.sporttery.cn/gateway/uniform/football/getFixedBonusV1.qry';
    const API_PARAMS = {
      clientCode: '3001',
      matchId: matchId
    };

    console.log(`正在获取比赛 ${matchId} 的赔率变化数据...`);
    const response = await axios.get(API_URL, { params: API_PARAMS });

    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    const oddsHistory = response.data.value.oddsHistory;
    const matchResults = response.data.value.matchResultList;

    // 格式化赔率历史数据
    const formattedOdds = {};

    // 遍历每种下注类型
    Object.entries(BET_TYPES).forEach(([typeKey, typeInfo]) => {
      const historyData = oddsHistory[typeInfo.key];
      if (historyData && historyData.length > 0) {
        formattedOdds[typeKey] = {
          type: typeInfo.name,
          description: typeInfo.description,
          history: historyData.map(record => {
            const formattedRecord = {
              updateDate: record.updateDate,
              updateTime: record.updateTime,
              odds: {},
              changes: {} // 记录变化标志
            };

            // 提取对应字段的赔率和变化标志
            typeInfo.fields.forEach(field => {
              if (record[field] !== undefined) {
                formattedRecord.odds[field] = record[field];
                // 获取变化标志（字段名+f）
                const changeFlag = record[field + 'f'];
                if (changeFlag !== undefined) {
                  formattedRecord.changes[field] = changeFlag;
                }
              }
            });

            // 特殊处理让球数
            if (record.goalLine !== undefined) {
              formattedRecord.goalLine = record.goalLine;
            }

            return formattedRecord;
          })
        };
      }
    });

    // 获取当前最新赔率
    const currentOdds = {};
    matchResults.forEach(result => {
      const betType = Object.keys(BET_TYPES).find(key => key === result.code);
      if (betType) {
        if (!currentOdds[betType]) {
          currentOdds[betType] = {};
        }
        currentOdds[betType][result.combination] = {
          odds: result.odds,
          description: result.combinationDesc,
          goalLine: result.goalLine
        };
      }
    });

    const result = {
      matchInfo: {
        matchId: oddsHistory.matchId,
        homeTeam: {
          id: oddsHistory.homeTeamId,
          name: oddsHistory.homeTeamAllName,
          abbName: oddsHistory.homeTeamAbbName
        },
        awayTeam: {
          id: oddsHistory.awayTeamId,
          name: oddsHistory.awayTeamAllName,
          abbName: oddsHistory.awayTeamAbbName
        },
        league: {
          id: oddsHistory.leagueId,
          name: oddsHistory.leagueAllName,
          abbName: oddsHistory.leagueAbbName
        }
      },
      oddsHistory: formattedOdds,
      currentOdds: currentOdds,
      betTypes: BET_TYPES,
      finalScore: response.data.value.sectionsNo999
    };

    console.log(`成功获取比赛 ${matchId} 的赔率变化数据`);
    return result;

  } catch (error) {
    console.error(`获取比赛 ${matchId} 赔率变化数据出错:`, error.message);
    throw error;
  }
}
/**
 * 根据下注类型获取特定赔率历史
 * @param {string} matchId - 比赛ID
 * @param {string} betType - 下注类型 (HAD, HHAD, CRS, TTG, HAFU)
 * @returns {Promise<Object>} 返回特定类型的赔率变化数据
 */
async function getOddsByType(matchId, betType) {
  try {
    const allOdds = await getOddsHistory(matchId);

    if (!BET_TYPES[betType]) {
      throw new Error(`不支持的下注类型: ${betType}`);
    }

    const typeData = allOdds.oddsHistory[betType];
    if (!typeData) {
      throw new Error(`比赛 ${matchId} 没有 ${BET_TYPES[betType].name} 数据`);
    }

    return {
      matchInfo: allOdds.matchInfo,
      betType: BET_TYPES[betType],
      data: typeData,
      currentOdds: allOdds.currentOdds[betType]
    };

  } catch (error) {
    console.error(`获取比赛 ${matchId} ${betType} 类型赔率数据出错:`, error.message);
    throw error;
  }
}

// 6 获取比赛开奖结果
/**
 * 获取比赛开奖结果
 * @param {string} matchId - 比赛ID
 * @returns {Promise<Object>} 返回开奖结果数据
 */
async function getMatchResults(matchId) {
  try {
    const API_URL = 'https://webapi.sporttery.cn/gateway/uniform/football/getFixedBonusV1.qry';
    const API_PARAMS = {
      clientCode: '3001',
      matchId: matchId
    };

    console.log(`正在获取比赛 ${matchId} 的开奖结果...`);
    const response = await axios.get(API_URL, { params: API_PARAMS });

    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    const oddsHistory = response.data.value.oddsHistory;
    const matchResults = response.data.value.matchResultList;
    const finalScore = response.data.value.sectionsNo999;

    // 解析最终比分
    const [homeScore, awayScore] = finalScore ? finalScore.split(':').map(Number) : [null, null];

    const results = {
      matchInfo: {
        matchId: oddsHistory.matchId,
        homeTeam: {
          id: oddsHistory.homeTeamId,
          name: oddsHistory.homeTeamAllName,
          abbName: oddsHistory.homeTeamAbbName
        },
        awayTeam: {
          id: oddsHistory.awayTeamId,
          name: oddsHistory.awayTeamAllName,
          abbName: oddsHistory.awayTeamAbbName
        },
        league: {
          id: oddsHistory.leagueId,
          name: oddsHistory.leagueAllName,
          abbName: oddsHistory.leagueAbbName
        }
      },
      finalScore: {
        home: homeScore,
        away: awayScore,
        display: finalScore
      },
      winningResults: []
    };

    // 从 matchResultList 中提取所有开奖结果
    matchResults.forEach(result => {
      const betTypeInfo = BET_TYPES[result.code];
      const winningResult = {
        code: result.code,
        typeName: betTypeInfo ? betTypeInfo.name : result.code,
        combination: result.combination,
        combinationDesc: result.combinationDesc,
        odds: result.odds,
        goalLine: result.goalLine,
        poolId: result.poolId
      };
      results.winningResults.push(winningResult);
    });

    return results;

  } catch (error) {
    console.error(`获取比赛 ${matchId} 开奖结果出错:`, error.message);
    throw error;
  }
}


async function init() {
  // 1 获取所有比赛数据
  const allMatches = await getFormattedMatches()

  // // 2.1 获取队伍所有历史比赛数据
  // const teamHistory = await getTeamHistoryMatches({
  //     gmTeamId: allMatches[0].homeTeam.id,
  //     termLimits: 20,
  // })
  // // 2.2 获取队伍主场历史记录
  // const teamHistoryHome = await getTeamHistoryMatches({
  //     gmTeamId: allMatches[0].homeTeam.id,
  //     termLimits: 20,
  //     homeAwayFlag: 'home',
  // })
  // // 2.3 获取队伍客场历史记录
  // const teamHistoryAway = await getTeamHistoryMatches({
  //     gmTeamId: allMatches[0].homeTeam.id,
  //     termLimits: 20,
  //     homeAwayFlag: 'away',
  // })

  // 3 获取比赛的积分榜数据
  // const matchTables = await formatTablesData(allMatches[3].matchId)

  // 4 获取赔率变化历史
  // const oddsData = await getOddsHistory('2033598');
  // const hadData = await getOddsByType('2033598', 'HAD'); // 胜平负
  // const hhadData = await getOddsByType('2033598', 'HHAD'); // 让球胜平负  
  // const crsData = await getOddsByType('2033598', 'CRS'); // 比分
  // const ttgData = await getOddsByType('2033598', 'TTG'); // 总进球数
  // const hafuData = await getOddsByType('2033598', 'HAFU'); // 半全场

  // 5 获取开奖结果
  // const results = await getMatchResults('2033598');
  console.log(allMatches);


}

init()